<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="年度电量" name="year">        <el-alert
          description="提示：数据采集截止时间为当年最后一日 08:30"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 10px"
        />
        <el-form :inline="true" :model="yearQuery" class="query-form" @submit.prevent>
          <el-form-item label="年份">
            <el-date-picker
              v-model="yearQuery.year"
              type="year"
              value-format="YYYY"
              placeholder="请选择年份"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="租户名称">
            <el-input
              v-model="yearQuery.qymc"
              placeholder="请输入租户名称"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="电表">
            <el-input
              v-model="selectedMeterLabel"
              placeholder="请选择电表"
              style="width: 180px"
              readonly
              @click="openMeterDialog('year')"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getYearList">查询</el-button>
            <el-button @click="resetYearQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="yearList"  style="margin-top: 10px">
          <el-table-column prop="dbbh" label="电表号" align="center" />
          <el-table-column prop="fjh" label="房间号" align="center" />
        
          <el-table-column prop="magnification" label="倍率" align="center" />
          <el-table-column prop="qymc" label="租户名称" align="center"  width="250" show-overflow-tooltip/>
          <el-table-column prop="nf" label="统计年份" align="center" />
          <el-table-column prop="lastReading" label="上年读数" align="center" />
          <el-table-column prop="currentReading" label="本年读数" align="center" />
          <el-table-column prop="used" label="用电量" align="center" />
        </el-table>
        <pagination
          v-show="yearTotal > 0"
          :total="yearTotal"
          v-model:page="yearQuery.pageNum"
          v-model:limit="yearQuery.pageSize"
          @pagination="getYearList"
        />
      </el-tab-pane>
      <el-tab-pane label="年分月电量" name="month">
        <el-form :inline="true" :model="yearMonthQuery" class="query-form" @submit.prevent>
          <el-form-item label="年份">
            <el-date-picker
              v-model="yearMonthQuery.year"
              type="year"
              value-format="YYYY"
              placeholder="请选择年份"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="电表">
            <el-input
              v-model="selectedMeterLabel"
              placeholder="请选择电表"
              style="width: 180px"
              readonly
              @click="openMeterDialog('yearMonth')"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getYearMonthList">查询</el-button>
            <el-button @click="resetYearMonthQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div style="display: flex; gap: 24px;">
          <div style="flex: 1;">
            <el-card>
              <div ref="chartRef" style="height: 550px;"></div>
            </el-card>
          </div>
          <div style="width: 320px;">
            <el-table :data="yearMonthList" border height="550" style="margin-top: 10px">
              <el-table-column prop="month" label="月份" align="center" />
              <el-table-column prop="used" label="用电量" align="center" />
            </el-table> 
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 电表选择弹窗 -->
    <el-dialog
      title="选择电表"
      v-model="meterDialogVisible"
      width="900px"
      append-to-body
    >
      <el-form :inline="true" :model="meterQuery" class="query-form" @submit.prevent>
        <el-form-item label="电表编号">
          <el-input v-model="meterQuery.dbbh" placeholder="请输入电表编号" style="width: 120px" />
        </el-form-item>
        <el-form-item label="智联器编号">
          <el-input v-model="meterQuery.zlid" placeholder="请输入智联器编号" style="width: 120px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getMeterList">查询</el-button>
          <el-button @click="resetMeterQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="meterTableRef"
        :data="meterDialogList"
        border
        height="500"
        highlight-current-row
        :row-key="row => row.dbbh"
        :current-row="selectedMeterRow"
        @current-change="handleMeterSelect"
        @selection-change="handleMeterSelectionChange"
        style="margin-bottom: 10px"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="() => true"
          :reserve-selection="false"
        />
        <el-table-column prop="qymc" label="租户名称" align="center"  width="250" show-overflow-tooltip />
        <el-table-column prop="dbbh" label="电表编号" align="center" />
        <el-table-column prop="zlid" label="智联器编号" align="center" />
      </el-table>
      <pagination
        v-show="meterTotal > 0"
        :total="meterTotal"
        v-model:page="meterQuery.pageNum"
        v-model:limit="meterQuery.pageSize"
        @pagination="getMeterList"
      />
      <template #footer>
        <el-button @click="meterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMeterSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { yearEnery, yearMonthEnery, selectAllAmmeter } from "@/api/energy/index";
import { Search } from "@element-plus/icons-vue";

const activeTab = ref("year");

// 获取本年字符串
function getCurrentYearStr() {
  return String(new Date().getFullYear());
}

// 年度电量查询
const yearQuery = reactive({
  year: getCurrentYearStr(), // 默认本年
  qymc: "",
  dbbh: "",
  pageNum: 1,
  pageSize: 10,
});
const yearList = ref([]);
const yearTotal = ref(0);

// 年分月电量查询
const yearMonthQuery = reactive({
  year: getCurrentYearStr(), // 默认本年
  dbbh: "", 
});
const yearMonthList = ref([]); 

// 电表选择弹窗相关
const meterDialogVisible = ref(false);
const meterQuery = reactive({
  dbbh: "",
  zlid: "",
  pageNum: 1,
  pageSize: 10,
});
const meterDialogList = ref([]);
const meterTotal = ref(0);
const selectedMeterRow = ref(null);
const selectedMeterLabel = ref(""); // 展示在输入框的电表编号
let meterSelectTarget = ""; // year/yearMonth

function openMeterDialog(target) {
  meterSelectTarget = target;
  meterDialogVisible.value = true;
  getMeterList();
}
function getMeterList() {
  selectAllAmmeter({ ...meterQuery }).then(res => {
    meterDialogList.value = res.data?.list || [];
    meterTotal.value = res.data?.total || 0;
  }).catch(() => {
    meterDialogList.value = [  ];
    meterTotal.value = 2;
  });
}
function resetMeterQuery() {
  meterQuery.dbbh = "";
  meterQuery.zlid = "";
  meterQuery.pageNum = 1;
  meterQuery.pageSize = 10;
  getMeterList();
}
function handleMeterSelect(row) {
  selectedMeterRow.value = row;
}
function confirmMeterSelect() {
  if (!selectedMeterRow.value) return;
  selectedMeterLabel.value = selectedMeterRow.value.dbbh;
  if (meterSelectTarget === "year") {
    // yearQuery.dbbh = selectedMeterRow.value.dbbh;
    yearQuery.dbbh = selectedMeterRow.value.dbbh; // 修改为获取dbbh
  } else if (meterSelectTarget === "yearMonth") {
    // yearMonthQuery.dbbh = selectedMeterRow.value.dbbh;
    yearMonthQuery.dbbh = selectedMeterRow.value.dbbh; // 修改为获取dbbh
  }
  meterDialogVisible.value = false;
}

// 只允许单选
const meterTableRef = ref(null);
function handleMeterSelectionChange(selection) {
  if (selection.length > 1) {
    const last = selection[selection.length - 1];
    selectedMeterRow.value = last;
    meterDialogList.value.forEach(row => {
      if (row !== last) {
        if (meterTableRef.value) {
          meterTableRef.value.toggleRowSelection(row, false);
        }
      }
    });
  } else {
    selectedMeterRow.value = selection[0] || null;
  }
}

// 获取年度电量数据
function getYearList() {
  yearEnery({ ...yearQuery }).then(res => {
    yearList.value = res.data?.list || [];
    yearTotal.value = res.data?.total || 0;
  }).catch(() => {
    yearList.value = [ 
    ];
    yearTotal.value = 2;
  });
}
function resetYearQuery() {
  yearQuery.year = getCurrentYearStr(); // 重置为本年
  yearQuery.qymc = "";
  yearQuery.dbbh = "";
  yearQuery.pageNum = 1;
  yearQuery.pageSize = 10;
  selectedMeterLabel.value = "";
  getYearList();
}

// 获取年分月电量数据
const chartRef = ref();
let chartInstance = null;
function getYearMonthList() {
  yearMonthEnery({ ...yearMonthQuery }).then(res => {
    yearMonthList.value = res.data|| []; 
    nextTick(drawChart);
  }).catch(() => {
    yearMonthList.value =  []
    console.log(yearMonthList.value);
    nextTick(drawChart);
  });
}
function resetYearMonthQuery() {
  yearMonthQuery.year = getCurrentYearStr(); // 重置为本年
  yearMonthQuery.dbbh = "";
  selectedMeterLabel.value = "";
  yearMonthList.value = [];
  nextTick(drawChart);
}

// ECharts 折线图
function drawChart() {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  const xData = yearMonthList.value.map(item => item.month);
  const yData = yearMonthList.value.map(item => item.used);
  chartInstance.setOption({
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: xData, name: "月份" },
    yAxis: { type: "value", name: "用电量" },
    series: [
      {
        data: yData,
        type: "line",
        smooth: true,
        name: "用电量"
      }
    ]
  });
  chartInstance.resize();
}

watch(yearMonthList, () => {
  nextTick(drawChart);
});

onMounted(() => {
  getYearList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.query-form {
  margin-bottom: 10px;
}
</style>